package com.party.admin.web.controller.mall;

import com.party.admin.biz.file.FileBizService;
import com.party.admin.biz.mall.MallShowSubjectBizService;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.output.mall.MallShowSubjectOutput;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.mall.*;
import com.party.core.service.mall.IMallShowCategoryService;
import com.party.core.service.mall.IMallShowSubjectService;
import com.party.core.service.mall.IMallShowSubjectTemplateService;
import com.party.core.service.mall.biz.GoodsShowCountBizService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * 商城导购主题
 *
 * @author cyl
 * @date 2017-8-16
 * @time 16:18
 */
@Controller
@RequestMapping(value = "/mall/showsubject")
public class MallShowSubjectController {
    @Value("#{party['shop.url.protocol']}")
    private String shopUrl;

    protected static Logger logger = LoggerFactory.getLogger(MallShowSubjectController.class);

    @Autowired
    private IMallShowSubjectService mallShowSubjectService;
    @Autowired
    private MallShowSubjectBizService mallShowSubjectBizService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private IMallShowSubjectTemplateService mallShowSubjectTemplateService;
    @Autowired
    private GoodsShowCountBizService goodsShowCountBizService;
    @Autowired
    private IMallShowCategoryService mallShowCategoryService;

    /**
     * 主题列表
     *
     * @param mallShowSubjectQuery 商城主题
     * @param page                 分页参数
     * @return 交互数据
     */
    @RequestMapping(value = "list")
    public ModelAndView subjectList(MallShowSubjectQuery mallShowSubjectQuery, Page page) {
        ModelAndView mv = new ModelAndView("mall/showSubjectList");
        page.setLimit(10);
        mv.addObject("page", page);
        List<MallShowSubjectOutput> list = mallShowSubjectBizService.list(mallShowSubjectQuery, page);
        mv.addObject("subjects", list);

        return mv;
    }

    /**
     * 编辑或发布主题
     *
     * @param id 主题id
     * @return
     */
    @RequestMapping(value = "subjectform")
    public ModelAndView subjectForm(String id) {
        ModelAndView mv = new ModelAndView("mall/showSubjectForm");

        if (StringUtils.isNotEmpty(id)) {
            MallShowSubject mss = mallShowSubjectService.get(id);
            mss.setContent(StringUtils.unescapeHtml4Video2Iframe(mss.getContent()));
            mss.setBuyInstruction(StringUtils.unescapeHtml4Video2Iframe(mss.getBuyInstruction()));
            mv.addObject("subject", mss);

            if (StringUtils.isNotEmpty(mss.getTemplateId())) {
                MallShowSubjectTemplate mallShowSubjectTemplate = mallShowSubjectTemplateService.get(mss.getTemplateId());
                mv.addObject("template", mallShowSubjectTemplate);
            }
        } else {
            MallShowSubjectTemplateQuery param = new MallShowSubjectTemplateQuery();
            param.setDelFlag("0");
            List<MallShowSubjectTemplate> templateList = mallShowSubjectTemplateService.list(param);
            mv.addObject("templateList", templateList);
        }

        return mv;
    }

    /**
     * 保存导购主题信息
     *
     * @param mallShowSubject 主题信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "save")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveShowSubject(MallShowSubject mallShowSubject) {
        boolean result = mallShowSubjectBizService.saveSubjectBiz(mallShowSubject);
        if (result) {
            try {
                String filePath = fileBizService.getUploadCIPath(mallShowSubject.getCreateBy(), MallShowSubjectBizService.SHOW_SUBJECT_FOLDER_NEW);
                String content = shopUrl + "subject?id=" + mallShowSubject.getId();
                fileBizService.uploadCloudOut(mallShowSubject.getId(), filePath, content, mallShowSubject.getCreateBy(), false);
            } catch (Exception e) {
                logger.error("上传机构主题二维码失败", e);
            }
            return AjaxResult.success();
        } else {
            return AjaxResult.error("保存失败");
        }
    }

    /**
     * 删除导购主题
     *
     * @param id 主题id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delShowSubject(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }

        // 先查询是否存在下级类型
        MallShowCategory categoryParam = new MallShowCategory();
        categoryParam.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        categoryParam.setSubjectId(id);
        List<MallShowCategory> categoryList = mallShowCategoryService.listPage(categoryParam, new Page(1, 1));
        if (CollectionUtils.isNotEmpty(categoryList)) {
            return AjaxResult.error("该机构主题下已有商品类型, 不能删除");
        }
        MallShowSubject mallShowSubject = mallShowSubjectService.get(id);
        boolean result = mallShowSubjectBizService.deleteSubjectBiz(id);
        if (result) {
            // 统计模板的机构数量
            try {
                goodsShowCountBizService.addOrgNum(mallShowSubject.getTemplateId(), mallShowSubject.getMemberId(), false);
            } catch (Exception e) {
                logger.error("删除机构主题时, 统计模板的机构数量异常", e);
            }
            return AjaxResult.success();
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 复制导购主题
     *
     * @param id 源id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "copy")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult copyShowSubject(String id) {
        if (StringUtils.isEmpty(id)) {
            return new AjaxResult(false);
        }
        try {
            MallShowSubject mallShowSubject = mallShowSubjectBizService.copySubjectBiz(id);
            try {
                String filePath = fileBizService.getUploadCIPath(mallShowSubject.getCreateBy(), MallShowSubjectBizService.SHOW_SUBJECT_FOLDER_NEW);
                String content = shopUrl + "subject?id=" + mallShowSubject.getId();
                fileBizService.uploadCloudOut(mallShowSubject.getId(), filePath, content, mallShowSubject.getCreateBy(), false);
            } catch (Exception e) {
                logger.error("上传机构主题二维码失败", e);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("复制主题异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("复制主题失败");
        }
    }

    @ResponseBody
    @RequestMapping("initQrCode")
    public AjaxResult initQrCode() {
        List<MallShowSubject> mallShowSubjectList = mallShowSubjectService.list(new MallShowSubject());
        for (MallShowSubject mallShowSubject : mallShowSubjectList) {
            String filePath = fileBizService.getUploadCIPath(mallShowSubject.getCreateBy(), "showSubject");
            String content = "mall/mall_show_goods.html?id=" + mallShowSubject.getId();
            String localPath = mallShowSubject.getCreateBy() + "/mallShowSubject/";
            fileBizService.uploadCloudOut(mallShowSubject.getId(), filePath, localPath, mallShowSubject.getId(), content, mallShowSubject.getCreateBy());
        }
        return AjaxResult.success();
    }

    /**
     * 选择专题
     *
     * @return
     */
    @RequestMapping("selectSubject")
    public ModelAndView selectSubject(MallShowSubject showSubject, Page page) {
        page.setLimit(7);
        showSubject.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        List<MallShowSubject> mallShowSubjectList = mallShowSubjectService.listPage(showSubject, page);
        ModelAndView mv = new ModelAndView("/mall/selectShowSubject");
        mv.addObject("subjectList", mallShowSubjectList);
        mv.addObject("showSubject", showSubject);
        mv.addObject("page", page);
        return mv;
    }
}
